package com.jeaven.intercepter;

import com.jeaven.instruction.Instruction;
import com.jeaven.instruction.returnInst;
import com.jeaven.rtda.Frame;
import com.jeaven.rtda.Thread;
import com.jeaven.rtda.heap.KMethod;

import java.util.Map;

public class Intercepter {
    // 解释器，解释执行 字节码指令
    public Intercepter() {
        super();
    }

    public void intercepte(KMethod kMethod, String[] args) {  // 先不考虑有参数输入的情况
        return;
    }

    public void intercepte(KMethod kMethod) {
        int maxStacks = kMethod.maxStacks;
        int maxLocals = kMethod.maxLocals;
        Map<Integer, Instruction> instructionMap = kMethod.instructionMap;
        Thread thread = new Thread(1024);
        Frame frame = new Frame(maxLocals, maxStacks, thread);
        thread.pushFrame(frame);
        loopExecute(thread, instructionMap);
    }


    public void loopExecute(Thread thread, Map<Integer, Instruction> instructionMap) {  // 暂时不考虑父类和接口的初始化
        Map<Integer, Instruction> insts = instructionMap;
        Frame frame = thread.popFrame();
        while(true) {
            int pc = frame.nextPC;
            thread.setPc(pc);
            Instruction inst = insts.get(pc);
            System.out.println(inst.debug(" ")); // debug
            inst.execute(frame);
            frame.nextPC += inst.offset();
            if(inst instanceof returnInst) {
                return;
            }
        }
    }


}
